package com.ruoyi.tongban.utils;

import com.ruoyi.tongban.utils.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class CameraUtils {
  /**
   * 输出Url
   */
  public static JSONObject printUrls(String enjlishName, String LoseTime, String appname){
    //过期时间
    String expirationTime = LoseTime;
    //Unix时间戳
    Long unixTime = getUnixTime(expirationTime);
    //推流防盗链
    String key = "fb3d0c3d3ec3303dce09806d55271c6d";
    String streamId = appname;
    //时间戳16进制
    String txTime = Integer.toHexString(unixTime.intValue()).toUpperCase();
    //获取md5 txSecret
    String txSecret = getMd5(key+streamId+txTime);
    //bizid
    String bizId = "49105";
    //视频推送url
    String pushUrl = "rtmp://49105.livepush.myqcloud.com/"+enjlishName+"/"+streamId+"?bizid="+bizId+"&txSecret="+txSecret+"&txTime="+txTime;
    //视频播放url rtmp
    String playUrlRtmp = "rtmp://bxhls.benxinkeji.cn/"+enjlishName+"/"+streamId;
    //视频播放url flv
    String playUrlFlv = "http://bxhls.benxinkeji.cn/"+enjlishName+"/"+streamId+".flv";
    //视频播放url hls
    String playUrlHls = "http://bxhls.benxinkeji.cn/"+enjlishName+"/"+streamId+".m3u8";
    JSONObject data = new JSONObject();
    data.put("master_url", pushUrl);
    data.put("http_url", playUrlHls);
    data.put("rtmp_url", playUrlRtmp);
    data.put("live_slave_url_flv", playUrlFlv);
    return data;
  }
  /**
   * 获取unix时间戳
   * @return
   * @throws Exception
   */
  public static Long getUnixTime (String dateStr) {

    try {

      DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      long epoch = df.parse(dateStr).getTime();

      return epoch/1000;

    } catch (ParseException e) {
      e.printStackTrace();
    }

    return 0L;
  }

  /**
   * 获取md5字符串
   * @param str
   * @return
   */
  public static String getMd5(String str) {

    MessageDigest md5 = null;
    try {

      md5 = MessageDigest.getInstance("MD5");

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    byte[] bs = md5.digest(str.getBytes());
    StringBuilder sb = new StringBuilder(40);
    for(byte x:bs) {
      if((x & 0xff)>>4 == 0) {
        sb.append("0").append(Integer.toHexString(x & 0xff));
      } else {
        sb.append(Integer.toHexString(x & 0xff));
      }
    }
    return sb.toString();
  }
}
